package org.lxg.spring.demo;

import lombok.extern.slf4j.Slf4j;
import org.lxg.spring.config.autobean.AutoBeanConfig;
import org.lxg.spring.config.noxmlcreatebean.BeanConfig;
import org.lxg.spring.pojo.GameDisc;
import org.lxg.spring.pojo.JuiceMaker;
import org.lxg.spring.pojo.NoXmlCreatBean;
import org.lxg.spring.pojo.Source;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@Slf4j
public class SpringIocDemo {
    public static void main(String[] args) {

        /**
         * Spring IoC
         *  Source 对象由 spring 创建 ，对象的生命周期由Spring来管理，直接从Spring那里去获取一个对象 无需 new
         */
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
        Source source = (Source) context.getBean("source");
        System.out.println(source.getFruit());
        System.out.println(source.getSugar());
        System.out.println(source.getSize());

        /**
         * Spting DI
         *  指 Spring 创建对象的过程中，将对象依赖属性（简单值，集合，对象）通过配置设值给该对象
         *  Source 对象 注入在 JuiceMaker 对象中 此时这两个对象都由spring管理
         */

        JuiceMaker juiceMaker = (JuiceMaker) context.getBean("juickMaker");
        System.out.println(juiceMaker.makeJuice());

        /**
         *  IoC 如何实现的
         *  1 读取标注或者配置文件，看看JuiceMaker依赖的是哪个Source，拿到类名
         *  2 使用反射的API，基于类名实例化对应的对象实例
         *  3 将对象实例，通过构造函数或者 setter，传递给 JuiceMaker
         */

        /**
         * 不通过xml 创建类
         */
        ApplicationContext contextConfig = new AnnotationConfigApplicationContext(BeanConfig.class);
        NoXmlCreatBean noXmlCreatBean = contextConfig.getBean(NoXmlCreatBean.class);
        noXmlCreatBean.setFiledOne("A");
        noXmlCreatBean.setFiledTwo(1);
        System.out.println(noXmlCreatBean.toString());

        //通过注册的方式
        AnnotationConfigApplicationContext acc = new AnnotationConfigApplicationContext();
        acc.register(NoXmlCreatBean.class);
        acc.refresh();
        NoXmlCreatBean noXmlCreatBean1 = contextConfig.getBean(NoXmlCreatBean.class);
        noXmlCreatBean1.setFiledOne("B");
        noXmlCreatBean1.setFiledTwo(2);
        System.out.println(noXmlCreatBean1.toString());

        /**
         * Spring 的的自动装配
         */
        ApplicationContext contextAutoConfig = new AnnotationConfigApplicationContext(AutoBeanConfig.class);
        GameDisc gameDisc = contextAutoConfig.getBean(GameDisc.class);
        gameDisc.setGamName("DOTA");
        gameDisc.setGameColor("RED");
        System.out.println(gameDisc.toString());
    }
}